package com.vvlive.caibao.smartcity.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhj on 2015/9/8.
 */
public class GsonUtil {

    private static Gson GSON ;

    public static <T> List<T> toList(String json, Class<T> cls){
        Type type = new TypeToken<List<T>>(){}.getType();
        List<T> temp = getGson().fromJson(json, type);
        List<T> list = new ArrayList<T>();
        for(T t : temp){
            T obj = toObject(toJson(t), cls);
            list.add(obj);
        }
        return list;
    }

    public static <T> T toObject(String json, Class<T> cls){
        return getGson().fromJson(json, cls);
    }

    public static String toJson(Object object){
        return getGson().toJson(object);
    }

    /**
     * 确保只有一个Gson实例
     * @return
     */
    private static Gson getGson(){
        if(GSON == null){
            GSON = new Gson();
        }
        return GSON;
    }
}
